#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

from pymongo import MongoClient
import pymongo
import sys


# 连接MongoDB
def InitMongoDB(MONGODB_HOST, MONGODB_PORT, MONGODB_DB_NAME, MONGODB_COLLECTION_NAME):
    client = MongoClient(MONGODB_HOST, MONGODB_PORT)
    db = client[MONGODB_DB_NAME]
    collection = db[MONGODB_COLLECTION_NAME]
    return client, collection


# 关闭MongoDB
def CloseMongoDB(MongoDB_Connection):
    MongoDB_Connection.close()


def FindHole(MONGODB_HOST, collection_name, interval):
    fieldmap = {"project": "proj_no", "experiment": "exp_no", "sample": "sap_no", "run": "run_no", "data": "dat_no",
                "analysis": "anal_no"}
    idmap = {"project": "NODEP", "experiment": "NODEX", "sample": "NODES", "run": "NODER", "data": "NODED",
             "analysis": "NODEZ"}

    client, collection = InitMongoDB(MONGODB_HOST, 27017, "node", collection_name)

    start = 10
    maxid = 10
    current_top = 0
    hole_count = 0
    total_length = 0

    field = fieldmap[collection_name]
    prefix = idmap[collection_name]

    results = collection.find().sort(field, pymongo.DESCENDING).limit(1)
    for result in results:
        maxid = int(result[field][5:])
        print("Start searching " + collection_name + " id holes, current max " + field + "=" + result[
            field] + ".")

    for i in range(start, maxid + 1, int(interval)):
        if i <= current_top:
            continue
        else:
            for item in collection.find({field: {"$lt": prefix + str(i).zfill(8)}}, {"_id": 0, field: 1}).sort(
                    field, pymongo.DESCENDING).limit(1):
                if item[field].startswith(prefix):
                    if i - int(item[field][5:]) >= 3:
                        for item2 in collection.find({field: {"$gt": prefix + str(i).zfill(8)}},
                                                     {"_id": 0, field: 1}).sort(field, pymongo.ASCENDING).limit(1):
                            if item2[field].startswith(prefix):
                                current_top = int(item2[field][5:])
                                hole_start = prefix + str(int(item[field][5:]) + 1).zfill(8)
                                hole_end = prefix + str(int(item2[field][5:]) - 1).zfill(8)
                                hole_len = int(item2[field][5:]) - int(item[field][5:]) - 1
                                hole_count += 1
                                total_length += hole_len
                                print("[" + collection_name.capitalize() + " hole " + str(
                                    hole_count) + "] StartID=" + hole_start + ", EndID=" + hole_end + ", length=" + str(
                                    hole_len) + ".")
                                break
                            else:
                                break
                    else:
                        break
                else:
                    break
    print("Finished. Find " + str(hole_count) + " holes, " + str(total_length) + " missing " + field + " in total.")

    CloseMongoDB(client)


if __name__ == '__main__':
    FindHole(sys.argv[1], "project", "1000")
    FindHole(sys.argv[1], "experiment", "1000")
    FindHole(sys.argv[1], "sample", "1000")
    FindHole(sys.argv[1], "run", "1000")
    FindHole(sys.argv[1], "data", "1000")
    FindHole(sys.argv[1], "analysis", "1000")
